<template>
    <div class="yu-form">
        <h1 class="yu-tit">登录</h1>
        <el-form :model="userinfo" :rules="rules" ref="userinfo" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userinfo.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="userinfo.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login('userinfo')">登录</el-button>
            </el-form-item>
        </el-form>
        <router-link to="/registry">没有账号去注册</router-link>
    </div>
</template>
<script>
import $api from '../api/index'
console.log("=====",$api)
export default {
    data(){
        return {
            userinfo:{
                username:'',
                password:''
            },
            //校验规则
            rules:{
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 4, max: 6, message: '长度在 4 到 6 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    methods:{
        login(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    $api.login({username:this.userinfo.username,password:this.userinfo.password}).then(res => {
                        if(res.code === 1){
                            this.$message({
                                message: '登录成功',
                                type: 'success'
                            });
                            localStorage.setItem('token',res.token);
                            localStorage.setItem('username',res.username);
                            localStorage.setItem('uid',res.uid);
                            this.$router.replace('/main/home');
                        }else{
                            this.$message.error('登录失败');
                        }
                    })    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
}
</script>

<style>
    .yu-form{
        width:400px;
        margin:200px auto;
        text-align: center;
    }
    .yu-tit{
        font-size:30px;
        margin-bottom:40px;
    }
</style>

